//
//  StickerKeyboard.m
//  CarLife
//
//  Created by yu on 2019/4/10.
//  Copyright © 2019年 jpas. All rights reserved.
//

#import "StickerKeyboard.h"
#import "PPStickerDataManager.h"
#import "StickerCell.h"
#import "PPUtil.h"
#import "PPSticker.h"
#import "PPEmoji.h"
#import "HorizontalFlowLayout.h"
#import "PPEmojiPreviewView.h"

static CGFloat const PPStickerScrollViewHeight = 132.0;
static CGFloat const PPKeyboardPageControlTopMargin = 10.0;
static CGFloat const PPKeyboardPageControlHeight = 7.0;
static CGFloat const PPKeyboardPageControlBottomMargin = 6.0;
static CGFloat const PPKeyboardCoverButtonHeight = 44.0;
static CGFloat const PPPreviewViewWidth = 92.0;
static CGFloat const PPPreviewViewHeight = 137.0;

static NSInteger const ItemCountPerPage = 28;

static NSString *const kDeleteButtonId = @"delete_emoji";
static NSString *const blankId = @"";

static NSString *const kIdentifier = @"sticker";


@interface StickerKeyboard ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSArray<PPEmoji *> *emojis;
@property (nonatomic, strong) PPEmojiPreviewView *emojiPreviewView;

@end


@implementation StickerKeyboard

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        NSArray<PPSticker *> *stickers = [PPStickerDataManager sharedInstance].allStickers.copy;
        PPSticker *sticker = stickers[0];
        self.emojis = [self emojisForSticker:sticker];
        
        self.backgroundColor = [UIColor whiteColor];
        
        HorizontalFlowLayout *flowLayout = [[HorizontalFlowLayout alloc] init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.minimumInteritemSpacing = 0;
        
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        self.collectionView.backgroundColor = [UIColor whiteColor];
        self.collectionView.dataSource = self;
        self.collectionView.delegate = self;
        self.collectionView.pagingEnabled = YES;
        self.collectionView.showsHorizontalScrollIndicator = NO;
        [self addSubview:self.collectionView];
        self.collectionView.contentInset = UIEdgeInsetsMake(0, 20, 0, 20);
        
        UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(didLongPressEmoji:)];
        longPressRecognizer.minimumPressDuration = 0.2;
        [self.collectionView addGestureRecognizer:longPressRecognizer];
        
        [self.collectionView registerNib:NIB_NAMED(@"StickerCell") forCellWithReuseIdentifier:kIdentifier];
        
        [self addSubview:self.pageControl];
        
        self.pageControl.sd_layout
        .leftSpaceToView(self, 0)
        .rightSpaceToView(self, 0)
        .bottomSpaceToView(self, 15)
        .heightIs(10);
        
        self.collectionView.sd_layout
        .leftSpaceToView(self, 0)
        .topSpaceToView(self, 10)
        .rightSpaceToView(self, 0)
        .bottomSpaceToView(_pageControl, 3);
        
    }
    return self;
}

- (void)didLongPressEmoji:(UILongPressGestureRecognizer *)recognizer {

    CGPoint point = [recognizer locationInView:self.collectionView];
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
    if (!indexPath) {
        [self hidePreviewViewForSuperview];
        return;
    }
    PPEmoji *emoji = self.emojis[indexPath.row];
    
    if (!emoji.imageName || [emoji.imageName isEqualToString:kDeleteButtonId]) {
        [self hidePreviewViewForSuperview];
        return;
    }

    StickerCell *cell = (StickerCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    
    CGRect cellFrame = cell.frame;

    switch (recognizer.state) {
       case UIGestureRecognizerStateBegan:
            [self showPreviewViewWithEmoji:emoji cellFrame:cellFrame];
            break;
       case UIGestureRecognizerStateChanged:
            [self showPreviewViewWithEmoji:emoji cellFrame:cellFrame];
            break;
        case UIGestureRecognizerStateEnded:
            [self hidePreviewViewForSuperview];
            if (self.delegate && [self.delegate respondsToSelector:@selector(stickerKeyboard:didClickEmoji:)]) {
                [self.delegate stickerKeyboard:self didClickEmoji:emoji];
            }
            break;
        default:
            [self hidePreviewViewForSuperview];
            break;
    }
}

- (void)showPreviewViewWithEmoji:(PPEmoji *)emoji cellFrame:(CGRect)cellFrame
{
    if (!emoji) {
        [self hidePreviewViewForSuperview];
        return;
    }
    
    self.emojiPreviewView.emoji = emoji;


    UIWindow *window = [UIApplication sharedApplication].windows.lastObject;
    
    CGRect cellFrameAtWindow = [window convertRect:cellFrame fromView:self.collectionView];
    
    self.emojiPreviewView.frame = CGRectMake(CGRectGetMidX(cellFrameAtWindow) - PPPreviewViewWidth / 2, CGRectGetMaxY(cellFrameAtWindow) - PPPreviewViewHeight, PPPreviewViewWidth, PPPreviewViewHeight);
    
    if (window) {
        [window addSubview:self.emojiPreviewView];
    }
}

- (void)hidePreviewViewForSuperview {
    [self.emojiPreviewView removeFromSuperview];
}


- (NSArray<PPEmoji *> *)emojisForSticker:(PPSticker *)sticker
{
    NSMutableArray *emojis = [NSMutableArray arrayWithArray:sticker.emojis];
    NSInteger page = emojis.count / ItemCountPerPage;//28个一页
    NSInteger needCount = ItemCountPerPage - emojis.count % ItemCountPerPage;
    if (needCount > 0) {
        for (NSInteger i = 0; i < needCount - page; i++) {
            PPEmoji *empty = [[PPEmoji alloc] init];
            [emojis addObject:empty];
        }
        
        for (NSInteger i = 0; i < emojis.count; i++) {
            if ((i + 1) % ItemCountPerPage == 0) {
                PPEmoji *emoji = [[PPEmoji alloc] init];
                emoji.imageName = kDeleteButtonId;
                [emojis insertObject:emoji atIndex:i];
            }
        }
        [emojis removeObject:[emojis lastObject]];
    }
    return emojis;
}


#pragma mark -

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.emojis.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    StickerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kIdentifier forIndexPath:indexPath];
//    int R = (arc4random() % 256);
//    int G = (arc4random() % 256);
//    int B = (arc4random() % 256);
//    [cell setBackgroundColor:[UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1]];
    PPEmoji *emoji = self.emojis[indexPath.row];
    cell.emojiImgView.image = [self emojiImageWithName:emoji.imageName];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PPEmoji *emoji = self.emojis[indexPath.row];
//    PPLog(@"ImageName = %@",emoji.imageName);
    
    if (!emoji.imageName) {return;}
    
    if ([emoji.imageName isEqualToString:kDeleteButtonId]) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(stickerKeyboardDidClickDeleteButton:)]) {
            [self.delegate stickerKeyboardDidClickDeleteButton:self];
        }
    } else {
        if (self.delegate && [self.delegate respondsToSelector:@selector(stickerKeyboard:didClickEmoji:)]) {
            [self.delegate stickerKeyboard:self didClickEmoji:emoji];
        }
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((CGRectGetWidth(_collectionView.bounds))/7, (CGRectGetHeight(_collectionView.bounds)-1)/4);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//- collection

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.pageControl.currentPage = scrollView.contentOffset.x / self.collectionView.frame.size.width;
}

- (CGFloat)heightThatFits
{
    CGFloat bottomInset = 0;
    if (@available(iOS 11.0, *)) {
        bottomInset = UIApplication.sharedApplication.delegate.window.safeAreaInsets.bottom;
    }
    return PPStickerScrollViewHeight + PPKeyboardPageControlTopMargin + PPKeyboardPageControlHeight + PPKeyboardPageControlBottomMargin + PPKeyboardCoverButtonHeight + 28;
}


- (UIPageControl *)pageControl
{
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] init];
        _pageControl.hidesForSinglePage = YES;
        _pageControl.numberOfPages = 4;
        _pageControl.currentPageIndicatorTintColor = [UIColor pp_colorWithRGBString:@"212121"];
        _pageControl.pageIndicatorTintColor = [UIColor pp_colorWithRGBString:@"D8D8D8"];
    }
    return _pageControl;
}

- (PPEmojiPreviewView *)emojiPreviewView
{
    if (!_emojiPreviewView) {
        _emojiPreviewView = [[PPEmojiPreviewView alloc] init];
    }
    return _emojiPreviewView;
}


- (UIImage *)emojiImageWithName:(NSString *)name
{
    if (!name.length) {
        return nil;
    }
    
    UIImage *image = [UIImage imageNamed:[@"Emoji.bundle" stringByAppendingPathComponent:name]];
    return image;
}

@end
